import dateUtils from 'ui-jz-v4-common/src/utils/date-utils';

// 时间格式化
export function parseTime(time, cFormat) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = cFormat || 'y-m-d h:i:s'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    // if (('' + time).length === 10) time = parseInt(time) * 1000
    date = new Date(time)
    // eslint-disable-next-line eqeqeq
    if (date == 'Invalid Date') return time
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/(y|m|d|h|i|s|a)/g, (result, key) => {
    let value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][value]
    }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}

export const longTime2Str = (t, fmt) => {
  return dateUtils.format(new Date(t), fmt || 'yyyy-MM-dd');
};

/**
 * 后端返回的字符串时间转Date
 * @param {String} str 后端返回的字符串
 * @param {String} inFmt 字符串输入格式 默认 yyyyMMddHHmmss
 * @param {String} outFmt 输出格式 默认 yyyy-MM-dd
 * @param {Boolean} isDate 是否输出Date 默认 是
 * @return {String|Date} 返回字符串或者日期
 */
export const strToDate = (str, inFmt, outFmt, isDate = true) => {
  return dateUtils.strToDate(str, inFmt, outFmt, isDate);
};

export const filterText = (str, r = '-') => {
  return str || r;
};


export const filterDate = (str, fmt = 'yyyy-MM-dd HH:mm:ss') => {
  if (str.length === 8) {
    fmt = 'yyyy-MM-dd'
  }
  return str ? longTime2Str(strToDate(str), fmt) : '-';
};